/**
 *	包名:	com.xx.common.util
 *	文件名:	BeanUtil.java
 *	描述:	对bean相关操作
 *	创建人:	qss
 *	创建时间:	2014-5-22下午5:45:34
 *	版权:	2014 xx版权所有
 */
package com.fh.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.sun.xml.internal.ws.util.UtilException;

public class BeanUtil {

	/**
	 * java bean 转换位map bean属性必须有对应的get set方法
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> bean2map(Object bean) {
		Map<String, Object> result = null;
		if (null != bean) {
			result = new HashMap<String, Object>();
			Method methods[] = bean.getClass().getDeclaredMethods();
			for (Method method : methods) {
				try {
					String name = method.getName();
					if (name.indexOf("get") == 0) {
						result.put(StringUtils.uncapitalize(name.substring(3, name.length())),
								method.invoke(bean, new Object[] {}));
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new UtilException(bean + "转换成map对象出错:" + e.getMessage());
				}
			}
			if (result.isEmpty()) {
				result = null;
			}
		}
		return result;
	}

	/**
	 * 
	 * TODO 方法作用：将map中对应key值获取封装到list中
	 * 
	 * @return
	 * @Author: 罗宝林
	 * @Date: 2014-6-6 下午1:21:15
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List<?> convertFieldToList(List<?> list, String fieldName) {
		List result = new ArrayList();
		Map<String, Object> map = null;
		for (int i = 0; i < list.size(); i++) {
			map = (Map<String, Object>) list.get(i);
			if (map.containsKey(fieldName)) {
				result.add(map.get(fieldName));
			}
		}
		return result;
	}

	/**
	 * @Description:把list转换为一个用逗号分隔的字符串
	 */
	public static String listToString(List<?> list) {
		StringBuilder sb = new StringBuilder();
		if ((list != null) && (list.size() > 0)) {
			for (int i = 0; i < list.size(); i++) {
				if (i < (list.size() - 1)) {
					sb.append(list.get(i) + ",");
				} else {
					sb.append(list.get(i));
				}
			}
		}
		return sb.toString();
	}

}
